package com.wkw.jkyf.config;

import com.wkw.jkyf.pojo.User;
import com.wkw.jkyf.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.Md5CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/*
权限认证
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    public IUserService userService;

    Md5CredentialsMatcher md5CredentialsMatcher = new Md5CredentialsMatcher();
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//         info.addRole();

//         info.addStringPermission("user:add");
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        this.setCredentialsMatcher(new Md5CredentialsMatcher());
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User queryUser = new User();
        queryUser.setUsername(username);
        //根据用户名查询用户是否存在
        User user = userService.queryUserByUserName(queryUser);
        if(user == null){//没有这个人
            return null; //抛出异常 UnknownAccountException
        }
        //当前用户
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        //
        //密码认证，shiro做~加密（获取当前用户的认证，传递密码的对象，认证名）
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
